/*
 * Created by Jaren at 2022/12/7 10:00
 */
import 'package:inmotion_protocol/base/base_message.dart';
import 'package:inmotion_protocol/base/protocol.dart';
import 'package:inmotion_protocol/common/riding_statistics_helper.dart';
import 'package:inmotion_protocol/lorin/bean/common/response/response.dart';
import 'package:inmotion_protocol/lorin/bean/euc/euc_statistics.dart';
import 'package:inmotion_protocol/util/log.dart';

/// EUC骑行记录统计数据helper
class EUCRidingStatisticsHelper extends RidingStatisticsHelper {
  static const maxRecordCountOnDevice = 64;

  EUCRidingStatisticsHelper(Protocol<IMessage> protocol) : super(protocol);

  @override
  Future<List<EucStatistics>> request({int fromId = 0}) {
    return requestStatisticsInfo().then((info) {
      if (fromId >= info.latestId) return [];
      int count2request = info.latestId - fromId;
      return requestStatistics(0, count2request).then((list) {
        if (list.isNotEmpty) list.removeAt(0);
        return list;
      });
    });
  }

  Future<StatisticsInfoResponse> requestStatisticsInfo() {
    return protocol.requestHistoryStatisticsInfo().catchError((e) => throw e);
  }

  Future<List<EucStatistics>> requestStatistics(int index, int count, {List<EucStatistics>? output}) {
    LogUtils.d("request statistics, index: $index, count: $count");
    output ??= [];
    return protocol.requestHistoryStatistics(index, count).then((rsp) async {
      if (rsp.count == 0 || count <= rsp.count) {
        // 目标数量不大于返回的数量或返回数量为0，获取结束
        output!.addAll(rsp.statisticsList.map((e) => e as EucStatistics));
        return output;
      }

      output!.addAll(rsp.statisticsList.map((e) => e as EucStatistics));
      // 继续请求剩余的
      return await requestStatistics(rsp.index + rsp.count, count - rsp.count, output: output);
    }).catchError((e) => throw e);
  }
}
